<template>
  <!-- 试验台账 -->
  <base-breadcrumb :title="$route.meta.title">
      <a-row :gutter="10" class="page-height">
        <a-col :span="4">
          <!-- 树搜索 -->
            <a-card
            style="border-right:1px solid #d9d9d9" 
              class="page-height-tree"
            >
            <tree-project
            ref="treeProject"
            :query="treeQuery"
            :auto-select="false"
            :selected-keys.sync="selectedKeys"
            @loader="search"
          />
          </a-card>
        </a-col>
        <a-col :span="20" class="page-height-list-wrapper" style="background:#fff">
          <searchData :search-data="searchArr" @search="search" />
          <!-- 表格 -->
          <div class="page-height-list">
            <list-table
              ref="table"
              row-key="id"
              :columns="columns"
              :request="loadData"
              @select-click="selectedClick"
              :select-config="{ use: true, type: 'checkbox', rowKey: 'id' }"
              :export-config="{ use: true, select: '试验台账选中', all: '试验台账全部', customColumns: customColumns }"
              :isShowCountBar="false"
            >
              <!-- 表格行操作栏 -->
              <span slot="action" slot-scope="text, record">
                <MoreButton>
                  <a v-btnPermission="[
                        {
                          ident: 'prma_seex',
                          code: 'seex_qm_024_loo_04'
                        },
                        {
                          ident: 'prma_buco',
                          code: 'buco_qm_024_loo_04'
                        }
                ]" @click="handleManage(2, record)">查看</a>
                  <template v-if="record.isOperation">
                    <a v-btnPermission="[
                        {
                          ident: 'prma_seex',
                          code: 'seex_qm_024_edi_02'
                        },
                        {
                          ident: 'prma_buco',
                          code: 'buco_qm_024_edi_02'
                        }
                ]" @click="handleManage(1, record)">编辑</a>
                    <a v-btnPermission="[
                        {
                          ident: 'prma_seex',
                          code: 'seex_qm_024_del_03'
                        },
                        {
                          ident: 'prma_buco',
                          code: 'buco_qm_024_del_03'
                        }
                ]" class="del_btn" @click="handleRemove(record)">删除</a>
                  </template>
                </MoreButton>
              </span>
              <span slot="prefix">
                <a-button v-btnPermission="[
                        {
                          ident: 'prma_seex',
                          code: 'seex_qm_024_add_01'
                        },
                        {
                          ident: 'prma_buco',
                          code: 'buco_qm_024_add_01'
                        }
                ]" icon="plus" type="primary" @click="handleManage(0)">
                  添加试验记录
                </a-button>
                <!-- v-btnPermission="'qm_024_add_01'" -->
                <a-button class="ml12" icon="import" type="primary" @click="importVisible = true" v-if="hideBuquBtn()"> 导入 </a-button>
                <!-- v-btnPermission="'qm_024_add_01'" -->
                <export-mould class="ml12" template-code="试验记录模板.xls" icon="cloud-download" />
              </span>
              <!-- 统计汇总 -->
              <AuditSummary ref="auditSummary" slot="bottom" title="试验台账" :countList="countList" />
            </list-table>
          </div>
        </a-col>
      </a-row>
    <!-- 表单弹窗 -->
    <dialog-form
      ref="dialogForm"
      :visible.sync="importVisible"
      edit-model="E"
      :form="{}"
      :forms.sync="forms"
      header-title="试验记录导入"
      :width="800"
      :rules="rules"
      :form-list="importForm"
      custom-footer
      @confirm="submitForm"
    >
      <!-- 附件 -->
      <template #fileArrays>
        <l-table business-code="QM04" :upload-arrys.sync="forms.fileArrays" :count="1" style="margin-bottom: -3px" />
      </template>
      <template slot="footer">
        <!-- 导入 -->
        <ExcelImportButton
          ref="excelImportButton"
          :disabled="importDisabled"
          class="btn_right"
          :loading="loading"
          @handleSubmit="handleSubmit"
        />
        <!-- 关闭 -->
        <a-button type="primary" @click="importVisible = false"> 关闭 </a-button>
      </template>
    </dialog-form>
  </base-breadcrumb>
</template>

<script>
import { STable } from '@/components' // 表格
import { experimentTable } from '@/api/quality/quality' // api
import Selector from '@/components/Select/Selector' // 通用下拉框
import TreeProject from '@/components/businessComponents/TreeProject' // 树
import DialogForm from '@/components/DialogForm' // 表单弹窗
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目名称
import ExportMould from '@/components/ExportMould' // 导出模板文件按钮
import SelectProjectStatus from '@/views/quality/components/SelectProjectStatus' // 项目状态
import AuditSummary from '@/views/quality/components/AuditSummary' // 统计汇总

const searchArr = [
  // 搜索框
  {
    name: '试件编号',
    value: 'specimenNumber',
    type: 'input'
  },
  {
    name: '试验项目（种类)',
    valueKey: 'experimentProject',
    type: Selector,
    selectType: '6'
  },
  {
    name: '规格',
    value: 'specification',
    type: 'input'
  },
  {
    name: '产地厂别',
    value: 'originSite',
    type: 'input'
  },
  {
    name: '部位',
    value: 'place',
    type: 'input'
  },
  {
    name: '送检时间',
    value: 'inspectionTime',
    type: 'dateRange',
    attr: {
      rangeFormat: ['inspectionTimeStart', 'inspectionTimeEnd']
    }
  },
  {
    name: '试验结果',
    valueKey: 'experimentResults',
    type: Selector,
    selectType: '7'
  },
  {
    name: '进场时间',
    value: 'entryTime',
    type: 'dateRange',
    attr: {
      rangeFormat: ['entryTimeStart', 'entryTimeEnd']
    }
  },
  {
    name: '归档时间',
    value: 'archiveTime',
    type: 'dateRange',
    attr: {
      rangeFormat: ['archiveBeginTime', 'archiveEndTime']
    }
  },
  {
    name: '项目状态',
    type: SelectProjectStatus,
    valueKey: 'projectStatus'
  }
]
const columns = [
  {
    title: '试件编号',
    dataIndex: 'specimenNumber',
    ellipsis: true
  },
  {
    title: '试验项目（种类)',
    dataIndex: 'experimentProjectName',
    ellipsis: true,
    customRender(text, record, index) {
      if (record.experimentProjectName && record.experimentProjectName.indexOf('其他') > -1) {
        return record.experimentProjectName + (record.otherExperimentProjectName ? '-'+ record.otherExperimentProjectName : '')
      } else {
        return record.experimentProjectName
      }
    },
  },
  {
    title: '试验结果',
    dataIndex: 'experimentResultsName',
    ellipsis: true
  },
  {
    title: '部位',
    dataIndex: 'place',
    ellipsis: true
  },
  {
    title: '规格',
    dataIndex: 'specification',
    ellipsis: true
  },
  {
    title: '产地厂别',
    dataIndex: 'originSite',
    ellipsis: true
  },
  {
    title: '进场时间',
    dataIndex: 'entryTime'
  },
  {
    title: '送检时间',
    dataIndex: 'inspectionTime'
  },
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    align: 'center',
    width: '180px',
    scopedSlots: { customRender: 'action' }
  }
]
const customColumns = [
  {
    title: '序号',
    dataIndex: 'index'
  },
  {
    title: '规格',
    dataIndex: 'specification'
  },
  {
    title: '试件编号',
    dataIndex: 'specimenNumber'
  },
  {
    title: '试验项目（种类)',
    dataIndex: 'experimentProjectName'
  },
  {
    title: '其他试验项目种类',
    dataIndex: 'otherExperimentProjectName'
  },
  {
    title: '部位',
    dataIndex: 'place'
  },
  {
    title: '进场时间',
    dataIndex: 'entryTime'
  },
  {
    title: '产地厂别',
    dataIndex: 'originSite'
  },
  {
    title: '委托编号',
    dataIndex: 'principalNum'
  },
  {
    title: '送检时间',
    dataIndex: 'inspectionTime'
  },
  {
    title: '报告编号',
    dataIndex: 'reportNum'
  },
  {
    title: '归档时间',
    dataIndex: 'archiveTime'
  },
  {
    title: '是否见证',
    dataIndex: 'isWitness'
  },
  {
    title: '试验结果',
    dataIndex: 'experimentResultsName'
  },
]
export default {
  name: 'a' + Date.now(),
  components: {
    STable,
    TreeProject,
    DialogForm,
    ExportMould,
    AuditSummary
  },
  computed: {
    // 表格列表请求参数
    args() {
      let args = this.queryParam
      // 添加分部分项id
      if (this.selectedKeys && this.selectedKeys.length > 0) {
        args.subItemId = this.selectedKeys[0]
      }
      return args
    },
    // 导入按钮禁用状态（当未选择项目和分公司时禁用）
    importDisabled() {
      return !this.forms?.projectId || !this.forms?.branchCompanyId
    }
  },
  data() {
    this.columns = columns
    this.customColumns = customColumns
    this.searchArr = searchArr
    return {
      treeQuery: {}, // 树列表请求参数
      loading: false, // 导入加载控件
      editModel: 0, // 操作类型：0 添加 1 编辑 3 查看
      selectedKeys: [], // 选中节点
      form: {}, // 表格行参数
      forms: {}, // 弹窗参数
      importVisible: false, // 导入弹窗显隐控件
      queryParam: {}, // 查询参数
      importForm: [
        {
          type: SelectSubCompany,
          keyName: 'branchCompanyId',
          label: '分公司名称',
          span: 12
        },
        {
          span: 12,
          type: SelectProject,
          keyName: 'projectId',
          label: '项目名称',
          attrs: {
            keyValue: 'branchCompanyId',
            form: this.forms
          }
        }
      ], // 导入表单列表
      loadData: (parameter) => {
        const requestParameters = Object.assign({}, parameter, this.args)
        return experimentTable.postList(requestParameters).then((res) => {
          // 更新汇总总数
          this.$nextTick(() => {
            this.$refs.auditSummary && this.$set(this.$refs.auditSummary.countInfo, 'total', res.totalSize)
          })
          return res
        })
      },
      countList: [
        {
          title: '总数：',
          value: 'total',
          needUnit: true
        },
        {
          key: 'select',
          title: '已选择',
          value: 0
        }
      ], // 汇总列表
      rules: {
        branchCompanyId: [{ required: true, message: '请选择分公司', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择项目', trigger: 'change' }]
      },
      importCheck: {
        规格: 'specification',
        试件编号: 'specimenNumber',
        '试验项目（种类）': 'experimentProjectName',
        其他试验项目种类: 'otherExperimentProjectName',
        部位: 'place',
        进场时间: 'entryTime',
        产地厂别: 'originSite',
        委托编号: 'principalNo',
        送检时间: 'inspectionTime',
        报告编号: 'reportNo',
        归档时间: 'archiveTime',
        是否见证: 'whetherToWitness',
        试验结果: 'experimentResultsName'
      },
      importCheck1: {
        规格: 'specification',
        试件编号: 'specimenNumber',
        '试验项目（种类）': 'experimentProjectName',
        部位: 'place',
        进场时间: 'entryTime',
        产地厂别: 'originSite',
        委托编号: 'principalNo',
        送检时间: 'inspectionTime',
        报告编号: 'reportNo',
        归档时间: 'archiveTime',
        是否见证: 'whetherToWitness',
        试验结果: 'experimentResultsName'
      },
      scrollerHeight:null
    }
  },
  mounted() {
    let that = this
    // 获取分项工程
    that.$refs.treeProject.getList()
  },
  methods: {
    selectedClick(e) {
      this.countList[1].value = e.rows.length
    },
    /**
     * 头部搜索
     */
    search(value) {
      // 赋值表单
      if (value) {
        this.queryParam = value
      }
      // 若存在项目状态，则先请求树，再请求表格
      if (value?.projectStatus) {
        this.treeQuery = {
          projectStatus: value.projectStatus
        }
        this.$refs.treeProject.getList().then(()=>{
          this.$refs.table?.refresh(true)
        })
      } else {
        this.$refs.table?.refresh(true)
      }
    },
    /**
     * 提交表单
     */
    submitForm(e) {
      let that = this
      let name = ['create', 'update'][that.editModel] // 根据操作切换url地址
      experimentTable[name](e)
        .then((res) => {
          // if (res.code == 200 || res.data.code == 200) {
          that.$refs.dialogProblem.loading = false
          that.$message.success(['添加', '编辑'][that.editModel] + '成功！')
          that.visible = false
          that.$refs.table.loadData()
          // } else {
          //   that.$message.warning(['添加', '编辑'][that.editModel] + '失败！')
          // }
        })
        .catch((res) => {
          that.$refs.dialogProblem.loading = false
        })
    },
    /**
     * 移除区域
     */
    handleRemove(e) {
      let that = this
      that.$confirm({
        title: '温馨提示',
        content: `确认删除？`,
        okText: '提交',
        cancelText: '关闭',
        onOk() {
          return experimentTable.remove({ id: e.id }).then((res) => {
            // if (res.code == 200 || res.data.code == 200) {
            that.$message.success('删除成功！')
            that.$refs.table.loadData()
            // } else {
            //   that.$message.warning('删除失败！')
            // }
          })
        }
      })
    },
    /**
     * 业务区域：新增/编辑/查看
     */
    handleManage(b, a) {
      // b 操作类型;a 行数据
      this.editModel = b
      let query = {
        editModel: b
      }
      if (b) {
        this.form = a
      } else {
        // console.log(this.selectedKeys)
        this.form = this.selectOptions
      }
      if (a) {
        query.id = a.id
      }
      this.$router.push({
        name: 'experimentTableEdit',
        query
      })
    },
    /**
     * 导入记录
     */
    handleSubmit(e) {
      console.log(e)
      let that = this
      let form = {
        list: []
      }
      for (let index in e) {
        let keys = e[index]
        form.list.push({
          experimentTable: {},
          projectInfo: {}
        })
        let listItem = form.list[index]
        // 校验excel的表头数量
        if ((keys['试验项目（种类）'] === '其他' && Object.keys(keys)?.length === 13) || (keys['试验项目（种类）'] !== '其他' && Object.keys(keys)?.length === 12)) {
          // 校验excel的表头字段
          let importCheck = this.importCheck
          if (keys['试验项目（种类）'] !== '其他') {
            importCheck = this.importCheck1
          }
          for (let i in importCheck) {
            let item = importCheck[i]
            if (!Object.keys(keys).includes(i)) {
              this.$message.warning(`${i}缺失`)
              return
            } else {
              if (item === 'entryTime' || item === 'inspectionTime' || item === 'archiveTime') {
                // 若是Date则转义，是字符串则校验格式
                if (keys[i] instanceof Date) {
                  listItem.experimentTable[item] = this.$dateFormat(keys[i].setDate(keys[i].getDate() - 1), 'D')
                } else if (!/^\d{4}-\d{2}-\d{2}$/.test(keys[i])) {
                  this.$message.warning(`${i}日期格式错误`)
                  return
                } else {
                  listItem.experimentTable[item] = keys[i]
                }
              } else {
                listItem.experimentTable[item] = keys[i]
                  item === 'whetherToWitness' ? { 是: '1', 否: '0' }[keys[i]] || '0' : keys[i]
              }
            }
          }
          // 添加项目和分公司信息
          listItem.projectInfo.projectId = this.forms.projectId
          listItem.projectInfo.branchCompanyId = this.forms.branchCompanyId
        } else {
          this.$message.warning('数据不完整')
          return
        }
      }
      // 发送请求
      that.loading = true
      experimentTable
        .imp(form.list)
        .then(() => {
          that.loading = false
          that.$message.success('导入成功！')
          that.$refs.table.loadData()
          that.importVisible = false
        })
        .catch(() => {
          that.loading = false
        })
    }
  }
}
</script>

